<?php
// +----------------------------------------------------------------------
// | 海豚PHP框架 [ DolphinPHP ]
// +----------------------------------------------------------------------
// | 版权所有 2016~2019 广东卓锐软件有限公司 [ http://www.zrthink.com ]
// +----------------------------------------------------------------------
// | 官方网站: http://dolphinphp.com
// +----------------------------------------------------------------------

namespace app\jzshop\admin;

use app\admin\controller\Admin;
use app\common\builder\ZBuilder;
use app\jzshop\job\mgt\MgtCreateJob;
use app\jzshop\job\mgt\MgtUpdateheadImageJob;
use app\jzshop\job\mgt\MgtUpdateJob as MgtMgtUpdateJob;
use app\jzshop\model\Brand;
use app\jzshop\model\GoodsSkuStandby;
use app\jzshop\model\Supplier as SupplierModel;
use think\Db;
use think\facade\View;
use think\Queue;

/**
 * 供应商控制器
 * @package app\jzshop\admin
 */
class Standby extends Admin
{
    /**
     * 供应商列表
     * @author 蔡伟明 <314013107@qq.com>
     * @return mixed
     * @throws \think\Exception
     * @throws \think\exception\DbException
     */
    public function index()
    {
        // 查询
        $map = $this->getMap();
        // 排序
        $order = $this->getOrder('id desc');
        // 数据列表
        $data_list = GoodsSkuStandby::where($map)->where('status > 0')->order($order)->paginate();

        // 使用ZBuilder快速创建数据表格
        return ZBuilder::make('table')
            ->setPageTips('debug:' . Db::getLastSql(), 'warning')

            ->setSearch([
                'brand_id' => '品牌',
                'itemName' => '商品名称',
                'itemNameAlias' => '商品别名',
                'colour' => '商品颜色',
                'colourAlias' => '商品颜色别名',
                'itemCode' => 'SKU编码',
                'itemCodeAlias' => 'SKU别名',
            ]) // 设置搜索框
            ->addColumns([ // 批量添加数据列
                ['id', 'ID'],
                ['right_button', '操作', 'btn'],
                ['brand_id', '品牌',   Brand::column('name', 'id')],
                ['main_img', '首图', 'picture'],
                ['main_img_alias', '首图', 'picture'],
                ['itemName', '商品名称', 'text'],
                ['itemNameAlias', '商品别名', 'text.edit'],
                ['colour', '商品颜色', 'text'],
                ['colourAlias', '商品编码别名', 'text.edit'],
                ['itemCode', 'SKU编码', 'text'],
                ['itemCodeAlias', 'SKU别名', 'text.edit'],
                ['supplyPrice', '供应价格', 'text'],
                ['spec', '尺寸', 'text'],
                ['weight', '重量', 'text'],
                // ['linePrice', '分销控价', 'text'],

                ['status', '状态', 'text', '', GoodsSkuStandby::STATUS],
                ['ypapp_status', '上架状态', 'text', '', GoodsSkuStandby::YPAPP_STATUS],

                ['right_button', '操作', 'btn']
            ])
            ->setTableName('jzshop_goods_standby')
            ->addRightButton('delete')
            ->addRightButton('edit', [
                'title' => '编辑',
                'icon'  => 'fa fa-fw fa-edit',

                'href'  => url('edit', ['id' => '__id__'])
            ]) // 批量添加顶部按钮       
            ->addRightButton('view', [
                'title' => '预览',
                'icon'  => 'fa fa-fw fa-eye',
                'href'  => url('view', ['id' => '__id__'])
            ], ['area' => ['600px', '90%']])
            ->addRightButton('link', [
                'title' => '聚水潭',
                'icon'  => 'fa fa-fw fa-rss-square',
                'target' => '_blank',
                'href'  => 'https://gyl.scm121.com/channel/goodsDetailNew/__itemSpuId__?itemCoId=__coId__'
            ])
            ->addRightButton('push', [
                'title' => '推送',
                'icon'  => 'fa fa-fw fa-upload',
                'class' => 'ajax-get',
                'href'  => url('push', ['type' => 'push', 'id' => '__id__'])
            ])
            ->addRightButton('push', [
                'title' => '更新',
                'icon'  => 'fa fa-fw fa-arrow-up',
                'class' => 'ajax-get',
                'href'  => url('push', ['type' => 'update', 'id' => '__id__'])
            ])
            ->addRightButton('push', [
                'title' => '更新头图',
                'icon'  => 'fa fa-fw fa-arrow-up',
                'class' => 'ajax-get',
                'href'  => url('push', ['type' => 'updateimage', 'id' => '__id__'])
            ])
            ->addRightButton('conflates', [
                'title' => '合并',
                'icon'  => 'fa fa-fw fa-file-code-o',
                'class' => 'ajax-get',
                'href'  =>  url('/jzshop/brand/conflates', ['id' => '__id__'])
            ])
            ->addTopButton('add')
            ->addTopButton('delete')
            ->addTopButton('push', [
                'title' => '批量推送',
                'icon'  => 'fa fa-fw fa-upload',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href'  => url('push', ['type' => 'push'])
            ])

            ->addTopButton('push', [
                'title' => '批量推送头图',
                'icon'  => 'fa fa-fw fa-upload',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href'  => url('push', ['type' => 'updateimage'])
            ])
            ->addTopButton('fastposter', [
                'title' => '设计器',
                'icon'  => 'fa fa-fw fa-magic',
                // 'field' => 'id',
                // 'target-form' => 'ids',
                'class' => 'btn btn-success',
                'href'  => module_config('jzshop.fastposter_url')
            ], true)

            ->addTopButton('push', [
                'title' => '批量合并',
                'icon'  => 'fa fa-fw fa-file-code-o',
                'field' => 'id',
                'target-form' => 'ids',
                'class' => 'btn btn-success ajax-post confirm',
                'href'  =>  url('/jzshop/brand/conflates')
            ])

            ->addOrder(['supplierId' => 'asc', 'itemSpuId' => 'asc', 'itemId' => 'desc'])
            ->setRowList($data_list) // 设置表格数据
            ->fetch(); // 渲染模板
    }
    public function edit($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['main_img_alias'] = $data['main_img'];
            if (GoodsSkuStandby::update($data)) {
                // 记录行为
                $this->success('编辑成功', 'index');
            } else {
                $this->error('编辑失败');
            }
        }

        $info = GoodsSkuStandby::get($id);

        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['select', 'brand_id', '品牌', '', Brand::column('id,name')],
                ['text', 'itemNameAlias', '商品名称'],
                ['text', 'colourAlias', '商品供应链ID'],
                ['text', 'itemCodeAlias', 'SKU编码'],
                ['image', 'main_img', '首图'],
                ['images', 'header_imgs', '首图'],
                ['images', 'body_imgs', '首图'],
            ])
            ->setTrigger('type', 2, 'logo')
            ->setFormData($info)
            ->fetch();
    }

    public function add()
    {
        // 保存数据
        if ($this->request->isPost()) {
            // 表单数据
            $data = $this->request->post();
            $data['main_img_alias'] = $data['main_img'];
            $data['status'] = 1;
            if (GoodsSkuStandby::create($data)) {
                // 记录行为
                $this->success('新增成功', 'index');
            } else {
                $this->error('新增失败');
            }
        }
        // 显示编辑页面
        return ZBuilder::make('form')
            ->addFormItems([
                ['hidden', 'id'],
                ['select', 'brand_id', '品牌', '', Brand::column('id,name')],
                ['text', 'itemNameAlias', '商品名称'],
                ['text', 'colourAlias', '商品供应链ID'],
                ['text', 'itemCodeAlias', 'SKU编码'],
                ['image', 'main_img', '首图'],
                ['images', 'header_imgs', '首图'],
                ['images', 'body_imgs', '首图'],
            ])
            ->fetch();
    }
    public function push($type = null)
    {

        if ($type === null) $this->error('参数错误!');

        $ids = $this->request->param('ids', false);
        $id = $this->request->param('id', false);

        if ($id || $ids) {

            if ($id) {
                $ids = [$id];
            }
        } else {
            $this->error('参数错误');
        }

        if (empty($ids)) {
            $this->error('参数错误');
        }
        $res = [];
        switch ($type) {
            case 'check':
                $res =   SupplierModel::checkStatus($ids);
                break;
            case 'image':
                $res =   SupplierModel::pushImage($ids);
                break;
            case 'update':
                foreach ($ids as $id) {
                    $res[] = Queue::push(MgtMgtUpdateJob::class, $id);
                }
                break;
            case 'updateimage':
                foreach ($ids as $id) {
                    $res[] = Queue::push(MgtUpdateheadImageJob::class, $id);
                }
                break;
            case 'push':
            default:
                foreach ($ids as $id) {
                    $res[] = Queue::push(MgtCreateJob::class, $id);
                }
                break;
        }


        if ($res) {
            $this->success('推送成功');
        } else {
            $this->error('推送失败');
        }
    }


    public function view($id = null)
    {
        if ($id === null) $this->error('缺少参数');

        $info = GoodsSkuStandby::where(['id' => $id])->find();

        $header_imgs = explode(',', $info['header_imgs']);

        View::assign('header', array_merge([$info['main_img_alias']], $header_imgs));
        View::assign('body', explode(',', $info['body_imgs']));
        View::assign('info', $info);
        View::assign('info', $info);

        return View::fetch();
    }
    public function quickEdit($record = [])
    {
        $param = $this->request->param();
        $res =   GoodsSkuStandby::where(['id' => $param['pk']])->update([$param['name'] => $param['value']]);
        if (false !== $res) {
            $this->success('操作成功');
        } else {
            $this->error('操作失败');
        }
    }


    /**
     * 删除
     * @param array $record 行为日志
     * @author 蔡伟明 <314013107@qq.com>
     * @throws \think\Exception
     * @throws \think\exception\PDOException
     */
    public function delete($record = [])
    {
        return $this->setStatus('disable');
        // return $this->setStatus('delete');
    }
}
